#include <raylib.h>
#include <iostream>
#include <string>
#include <memory>

// 常量定义
namespace Constants {
    const int DEFAULT_SCREEN_WIDTH = 800;
    const int DEFAULT_SCREEN_HEIGHT = 800;
    const int TARGET_FPS = 60;
    const std::string WINDOW_TITLE = "图片显示程序 - 可调整窗口";
    const std::string FLOOR_TEXTURE_PATH = "../assets/imgs/floors/floor.png";
}

// 纹理管理类
class TextureManager {
private:
    Texture2D texture;
    std::string filePath;
    bool loaded;

public:
    TextureManager(const std::string& path) : filePath(path), loaded(false) {
        texture = LoadTexture(path.c_str());
        if (texture.id != 0) {
            loaded = true;
            std::cout << "纹理加载成功: " << path << std::endl;
        } else {
            std::cerr << "纹理加载失败: " << path << std::endl;
        }
    }

    ~TextureManager() {
        if (loaded) {
            UnloadTexture(texture);
            std::cout << "纹理已卸载: " << filePath << std::endl;
        }
    }

    bool isLoaded() const { return loaded; }
    Texture2D getTexture() const { return texture; }
    int getWidth() const { return texture.width; }
    int getHeight() const { return texture.height; }
};

// 屏幕管理类
class ScreenManager {
private:
    int initialWidth;
    int initialHeight;
    std::string title;
    bool initialized;
    bool resizable;

public:
    ScreenManager(int w = Constants::DEFAULT_SCREEN_WIDTH, 
                  int h = Constants::DEFAULT_SCREEN_HEIGHT, 
                  const std::string& t = Constants::WINDOW_TITLE, 
                  bool resizable = true)  // 默认改为可调整大小
        : initialWidth(w), initialHeight(h), title(t), 
          initialized(false), resizable(resizable) {
        initialize();
    }

    ~ScreenManager() {
        if (initialized) {
            CloseWindow();
            std::cout << "窗口已关闭" << std::endl;
        }
    }

private:
    void initialize() {
        // 设置窗口可调整大小标志
        if (resizable) {
            SetConfigFlags(FLAG_WINDOW_RESIZABLE);
        }
        
        InitWindow(initialWidth, initialHeight, title.c_str());
        
        if (IsWindowReady()) {
            initialized = true;
            std::cout << "窗口初始化成功: " << initialWidth << "x" << initialHeight << std::endl;
            if (resizable) {
                std::cout << "窗口设置为可调整大小" << std::endl;
            }
        } else {
            std::cerr << "窗口初始化失败" << std::endl;
        }
    }

public:
    bool isReady() const { return initialized; }
    int getWidth() const { return GetScreenWidth(); }  // 实时获取当前宽度
    int getHeight() const { return GetScreenHeight(); } // 实时获取当前高度
    int getInitialWidth() const { return initialWidth; }
    int getInitialHeight() const { return initialHeight; }
    bool isResizable() const { return resizable; }
    
    void setTargetFPS(int fps) { 
        if (initialized) SetTargetFPS(fps); 
    }
    
    bool shouldClose() const { 
        return initialized ? WindowShouldClose() : true; 
    }
    
    // 新增：获取窗口尺寸变化信息
    bool isWindowResized() const {
        return IsWindowResized();
    }
    
    // 新增：最小尺寸限制
    void setMinWindowSize(int minWidth, int minHeight) {
        SetWindowMinSize(minWidth, minHeight);
    }
};

// 渲染器类
class Renderer {
public:
    static void beginFrame() { BeginDrawing(); }
    static void endFrame() { EndDrawing(); }
    
    static void clearBackground(Color color = WHITE) {
        ClearBackground(color);
    }
    
    static void drawTexture(const Texture2D& texture, int x, int y, Color tint = WHITE) {
        DrawTexture(texture, x, y, tint);
    }
    
    static void drawTextureCentered(const Texture2D& texture, int screenWidth, int screenHeight, Color tint = WHITE) {
        int x = (screenWidth - texture.width) / 2;
        int y = (screenHeight - texture.height) / 2;
        drawTexture(texture, x, y, tint);
    }
    
    // 新增：按比例缩放纹理
    static void drawTextureScaled(const Texture2D& texture, int screenWidth, int screenHeight, Color tint = WHITE) {
        float scaleX = (float)screenWidth / texture.width;
        float scaleY = (float)screenHeight / texture.height;
        float scale = (scaleX < scaleY) ? scaleX : scaleY; // 保持宽高比
        
        int scaledWidth = (int)(texture.width * scale);
        int scaledHeight = (int)(texture.height * scale);
        int x = (screenWidth - scaledWidth) / 2;
        int y = (screenHeight - scaledHeight) / 2;
        
        DrawTextureEx(texture, (Vector2){(float)x, (float)y}, 0.0f, scale, tint);
    }
    
    static void drawText(const std::string& text, int x, int y, int fontSize, Color color = DARKGRAY) {
        DrawText(text.c_str(), x, y, fontSize, color);
    }
    
    static void drawTextureInfo(const Texture2D& texture, int screenWidth, int screenHeight) {
        std::string info = "png size: " + std::to_string(texture.width) + "x" + std::to_string(texture.height);
        drawText(info, 10, screenHeight - 60, 18, DARKGRAY);
        
        std::string windowInfo = "screen size: " + std::to_string(screenWidth) + "x" + std::to_string(screenHeight);
        drawText(windowInfo, 10, screenHeight - 30, 18, DARKGRAY);
    }
};

// 应用程序主类
class Application {
private:
    std::unique_ptr<ScreenManager> screen;
    std::unique_ptr<TextureManager> texture;
    bool running;
    bool scaleToFit;  // 新增：是否按比例缩放

public:
    Application() : running(false), scaleToFit(true) {}  // 默认开启缩放
    
    bool initialize() {
        std::cout << "正在初始化应用程序..." << std::endl;
        
        // 初始化屏幕（设置为可调整大小）
        screen = std::make_unique<ScreenManager>(
            Constants::DEFAULT_SCREEN_WIDTH, 
            Constants::DEFAULT_SCREEN_HEIGHT, 
            Constants::WINDOW_TITLE, 
            true  // 设置为可调整大小
        );
        
        if (!screen->isReady()) {
            std::cerr << "屏幕初始化失败" << std::endl;
            return false;
        }
        
        // 设置最小窗口尺寸
        screen->setMinWindowSize(400, 300);
        
        // 加载纹理
        texture = std::make_unique<TextureManager>(Constants::FLOOR_TEXTURE_PATH);
        if (!texture->isLoaded()) {
            std::cerr << "纹理加载失败" << std::endl;
        }
        
        screen->setTargetFPS(Constants::TARGET_FPS);
        running = true;
        
        std::cout << "应用程序初始化成功" << std::endl;
        return true;
    }
    
    void run() {
        if (!running) {
            std::cerr << "应用程序未正确初始化" << std::endl;
            return;
        }
        
        std::cout << "开始主循环..." << std::endl;
        
        // 主循环
        while (running && !screen->shouldClose()) {
            handleInput();
            update();
            render();
        }
        
        std::cout << "主循环结束" << std::endl;
    }
    
    void shutdown() {
        std::cout << "正在关闭应用程序..." << std::endl;
        running = false;
        texture.reset();
        screen.reset();
        std::cout << "应用程序已关闭" << std::endl;
    }

private:
    void handleInput() {
        if (IsKeyPressed(KEY_ESCAPE)) {
            running = false;
        }
        
        // 新增：切换缩放模式
        if (IsKeyPressed(KEY_SPACE)) {
            scaleToFit = !scaleToFit;
            std::cout << "缩放模式: " << (scaleToFit ? "按比例缩放" : "原始尺寸") << std::endl;
        }
        
        // 新增：检测窗口尺寸变化
        if (screen->isWindowResized()) {
            std::cout << "windows size change: " << screen->getWidth() << "x" << screen->getHeight() << std::endl;
        }
    }
    
    void update() {
        // 可以在这里添加更新逻辑
    }
    
    void render() {
        Renderer::beginFrame();
        Renderer::clearBackground(WHITE);
        
        int currentWidth = screen->getWidth();
        int currentHeight = screen->getHeight();
        
        // 检查纹理是否加载成功
        if (texture && texture->isLoaded()) {
            if (scaleToFit) {
                // 按比例缩放显示
                Renderer::drawTextureScaled(
                    texture->getTexture(), 
                    currentWidth, 
                    currentHeight
                );
            } else {
                // 原始尺寸居中显示
                Renderer::drawTextureCentered(
                    texture->getTexture(), 
                    currentWidth, 
                    currentHeight
                );
            }
        } else {
            // 如果纹理加载失败，显示错误信息
            Renderer::drawText("纹理加载失败: " + Constants::FLOOR_TEXTURE_PATH, 
                             10, 50, 20, RED);
        }
        
        // 绘制UI信息
        Renderer::drawTextureInfo(texture->getTexture(), currentWidth, currentHeight);
        Renderer::drawText("Press ESC to exit", 10, 10, 20, DARKGRAY);
        Renderer::drawText("Press space to change zoom mode", 10, 35, 20, DARKGRAY);
        
        std::string modeText = "now mode " + std::string(scaleToFit ? "scale up and down" : "original size");
        Renderer::drawText(modeText, currentWidth - 250, 10, 20, DARKGRAY);
        
        Renderer::endFrame();
    }
};

int main() {
    std::cout << "程序启动..." << std::endl;
    
    Application app;
    
    if (app.initialize()) {
        app.run();
        app.shutdown();
        std::cout << "程序正常退出" << std::endl;
    } else {
        std::cerr << "应用程序初始化失败，程序退出" << std::endl;
        return -1;
    }
    
    return 0;
}